﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Agile.Engine.Service
{
    public interface ITaskAllocator
    {
        string Allocation(string args);
    }

    /// <summary>
    /// 任务分配器
    /// </summary>
    public abstract class TaskAllocator : ITaskAllocator
    {
        public TaskAllocator()
        {
            //AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
        }

        /// <summary>
        /// 分发服务
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public string Allocation(string args)
        {
            ///异步执行
            var asyn = new Func<string>(() =>
            {
                try
                {

                    ///分配流程
                    ///解析参数
                    var parse = Parse(args);
                    ///是否重定向
                    if (IsRedirect(parse))
                    {
                        return ExecuteRedirect(parse);
                    }

                    var task = ExecuteTask(parse);
                    return ProcessResult(task);

                }
                catch (Exception ex)
                {
                    return ProcessException(ex);
                }
            });
            var ar = asyn.BeginInvoke(new AsyncCallback(AsyncCallbackFunc), null);
            return asyn.EndInvoke(ar);
        }

        void AsyncCallbackFunc(IAsyncResult ar) { }

        /// <summary>
        /// 是否重定向
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract bool IsRedirect(object args);

        /// <summary>
        /// 执行重定向
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract string ExecuteRedirect(object args);

        /// <summary>
        /// 解析参数
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract object Parse(string args);

        /// <summary>
        /// 处理结果
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract string ProcessResult(object args);

        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public abstract string ProcessException(Exception ex);

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public abstract object ExecuteTask(object args);
    }
}
